package cn.texous.easytalk.manager.controller.user;

import cn.texous.easytalk.commonutil.constant.Result;
import cn.texous.easytalk.commonutil.constant.ResultCode;
import cn.texous.easytalk.manager.controller.BaseController;
import cn.texous.easytalk.manager.model.dto.UserDto;
import cn.texous.easytalk.manager.model.dto.UserLoginDto;
import cn.texous.easytalk.manager.model.params.user.UserLoginParam;
import cn.texous.easytalk.manager.model.params.user.UserNameValidateParam;
import cn.texous.easytalk.manager.model.params.user.UserRegisterParam;
import cn.texous.easytalk.manager.service.api.EtUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/9/2 14:57
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Api(value = "用户管理", tags = "用户管理接口")
public class UserController extends BaseController {

    @Autowired
    private EtUserService etUserService;

    @PostMapping("/validate/username")
    @ApiOperation(value = "校验用户名是否被使用")
    public Result<Boolean> validateUsername(@RequestBody @Valid UserNameValidateParam param) {
        String username = param.getUsername();
        if (StringUtils.isEmpty(username))
            return Result.paramFail("用户名为空");
        return Result.ok(etUserService.existsUsername(username));
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册接口")
    public Result<Boolean> register(@Valid @RequestBody UserRegisterParam param) {
        if (etUserService.existsUsername(param.getUsername()))
            return Result.out(ResultCode.USER_EXISTS_ERROR);
        Boolean result = etUserService.register(param);
        return Result.ok(result);
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口")
    public Result<UserLoginDto> login(@RequestBody @Valid UserLoginParam param) {
        if (!etUserService.existsUsername(param.getUsername()))
            return Result.out(ResultCode.USER_NOT_EXISTS_ERROR);
        UserLoginDto userLoginDto = etUserService.login(param);
        if (userLoginDto == null)
            return Result.out(ResultCode.USERNAME_PASSWORD_ERROR);
        return Result.ok(userLoginDto);
    }

    @PostMapping("/logout")
    @ApiOperation(value = "退出登录接口")
    public Result<Boolean> logout() {
        UserDto userDto = currentUser();
        return Result.ok(etUserService.logout(getToken(), userDto));
    }

}
